package org.mtmi.ui.controls;

import org.eclipse.swt.graphics.GC;
import org.eclipse.swt.graphics.Point;
import org.mtmi.ui.GraphicUtil;
import org.mtmi.ui.actions.Action;
import org.mtmi.ui.actions.IAction;
import org.mtmi.ui.actions.IActionListener;
import org.mtmi.ui.drawables.IDrawable;
import org.mtmi.ui.layouts.LayoutData;
import org.mtmi.ui.scenes.FontManager;
import org.mtmi.ui.scenes.Scene;

/**
 * Button associated to an action. Mainly made to take place in a tool bar.
 */
public class ToolBarButton extends AbstractButton
  implements IActionListener
{
	private IAction action;
	
	public ToolBarButton( Scene scene, IAction a, int flags) {
		super(scene, flags);
		assert( action!= null );
		action = a;
		setSize( computeSize( new LayoutData(scene) ) );
		setEnabled( a.isEnabled() );
		if( a instanceof Action ) ((Action)a).addActionListener( this );
	}

	@Override
	public void dispose() {
		super.dispose();
		if( action instanceof Action ) ((Action)action).removeActionListener( this );
	}
	
	public IAction getAction() { return action; }
	
	@Override
	public Point computeSize(LayoutData l) {
		IDrawable d = action.getImage();
		Point sz;
		if( d!=null ) {
			sz = d.computeSize( 0, 0 );
		}
		else {
			String s = action.getText();
			if( s==null || s.isEmpty() ) s = "?"; //$NON-NLS-1$
			l.gc.setFont( FontManager.getInstance().getToolBarFont() );
			sz = l.gc.textExtent( s );
		}
		//add margins:
		sz.x += 10; sz.y+=10;
		return sz;
	}
	
	@Override
	public boolean containsTouch( TouchControlEvent e ) {
		return GraphicUtil.rectContains( location, size, e.x, e.y );
	}

	@Override
	public void paint( GC gc ) {
		IDrawable d = action.getImage();
		
/*		if( isTapped ) {
			gc.setBackground( COLOR.ListSelectionBackground );
			gc.fillRectangle( location.x, location.y, size.x, size.y );
		} */
		
		if( d!=null ) {
			Point sz = d.computeSize( size.x-10, size.y-10 );
			int x = location.x+(size.x-sz.x)/2;
			int y = location.y+(size.y-sz.y)/2;
			int state = isEnabled ? ( isTapped ? IDrawable.PRESSED : IDrawable.NORMAL ) : IDrawable.DISABLED;
			d.paint( gc, x, y, sz.x, sz.y, state );
		}
		else {
			String s = action.getText();
			if( s==null || s.isEmpty() ) s = "?"; //$NON-NLS-1$
			gc.setFont( FontManager.getInstance().getToolBarFont() );
			Point sz = gc.textExtent( s );
			int x = location.x+(size.x-sz.x)/2;
			int y = location.y+(size.y-sz.y)/2;
			gc.drawText( s, x, y, true );
		}
	}

	@Override
	public void actionChanged( IAction _action ) {
		//note: not it's layouted by ToolBar: setSize( computeSize( new LayoutData(scene) ) );
		setEnabled( action.isEnabled() );
		redraw();
	}

}
